<!--
 * @Author: wangzhichiao<https://github.com/wzc570738205>
 * @Date: 2020-11-03 17:46:23
 * @LastEditors: wangzhichiao<https://github.com/wzc570738205>
 * @LastEditTime: 2020-11-05 10:46:11
-->
<template>
  <div>
    <el-upload
      class="form-uploader"
      :action="`${$baseUrl}`"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="img">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'UploadImg',
  props: {
    imageUrl: {
      type: String,
      default: () => {
        return null
      }
    }
  },
  methods: {
    beforeUpload(file) {
      console.log(file.type)
      const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    },
    handleSuccess(res, file) {
      this.$message.success('图片上传成功')
      console.log(this.$attrs)
      this.$attrs['handle-success'] && this.$attrs['handle-success'](res, file)
    }
  }
}
</script>

<style lang="scss" scoped>
.form-uploader {
  width: 100px;
  height: 100px;
  line-height: 100px;
  border: 1px dashed #c0ccda;
  text-align: center;
  & ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .img {
    max-width: 98px;
    max-height: 98px;
  }
}
</style>
